<template>
  <div class="settings-container">
    <div class="page-header">
      <h1>系统设置</h1>
    </div>
    
    <!-- 导航标签 -->
    <div class="settings-tabs">
      <button 
        v-for="tab in tabs" 
        :key="tab.id"
        :class="['tab-button', { active: activeTab === tab.id }]"
        @click="activeTab = tab.id"
      >
        {{ tab.name }}
      </button>
    </div>
    
    <!-- 基本设置 -->
    <div v-if="activeTab === 'basic'" class="settings-content">
      <div class="settings-card">
        <h2 class="card-title">基本设置</h2>
        <form @submit.prevent="saveBasicSettings">
          <div class="form-row">
            <div class="form-group">
              <label>网站名称</label>
              <input v-model="basicSettings.siteName" type="text" required />
            </div>
            <div class="form-group">
              <label>网站域名</label>
              <input v-model="basicSettings.siteUrl" type="text" required />
            </div>
          </div>
          <div class="form-row">
            <div class="form-group">
              <label>每页显示视频数</label>
              <input v-model.number="basicSettings.videosPerPage" type="number" min="1" max="50" required />
            </div>
            <div class="form-group">
              <label>评论审核</label>
              <select v-model="basicSettings.commentModeration">
                <option value="auto">自动通过</option>
                <option value="manual">手动审核</option>
                <option value="none">关闭评论</option>
              </select>
            </div>
          </div>
          <div class="form-group">
            <label>网站描述</label>
            <textarea v-model="basicSettings.siteDescription" rows="3"></textarea>
          </div>
          <div class="form-group">
            <label>启用注册</label>
            <div class="checkbox-group">
              <input id="enableRegistration" v-model="basicSettings.enableRegistration" type="checkbox" />
              <label for="enableRegistration">允许新用户注册</label>
            </div>
          </div>
          <div class="form-group">
            <label>启用评论</label>
            <div class="checkbox-group">
              <input id="enableComments" v-model="basicSettings.enableComments" type="checkbox" />
              <label for="enableComments">允许用户发表评论</label>
            </div>
          </div>
          <div class="form-group">
            <label>启用视频上传</label>
            <div class="checkbox-group">
              <input id="enableUploads" v-model="basicSettings.enableUploads" type="checkbox" />
              <label for="enableUploads">允许用户上传视频</label>
            </div>
          </div>
          <div class="form-actions">
            <button type="button" class="reset-button" @click="resetBasicSettings">重置</button>
            <button type="submit" class="save-button">保存设置</button>
          </div>
        </form>
      </div>
    </div>
    
    <!-- 管理员管理 -->
    <div v-if="activeTab === 'admins'" class="settings-content">
      <div class="settings-card">
        <div class="card-header">
          <h2 class="card-title">管理员账户</h2>
          <button class="add-button" @click="showAddAdminDialog = true">
            <i class="fa fa-plus"></i>
            添加管理员
          </button>
        </div>
        <div class="admins-list">
          <table class="admins-table">
            <thead>
              <tr>
                <th>用户名</th>
                <th>角色</th>
                <th>邮箱</th>
                <th>创建时间</th>
                <th>状态</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="admin in admins" :key="admin.id">
                <td>{{ admin.username }}</td>
                <td>
                  <span class="role-badge" :class="admin.role">
                    {{ admin.role === 'superadmin' ? '超级管理员' : '管理员' }}
                  </span>
                </td>
                <td>{{ admin.email }}</td>
                <td>{{ formatDate(admin.createdTime) }}</td>
                <td>
                  <span class="status-badge" :class="admin.status">
                    {{ admin.status === 'active' ? '活跃' : '禁用' }}
                  </span>
                </td>
                <td>
                  <div class="table-actions">
                    <button 
                      class="action-btn edit-btn" 
                      :disabled="admin.role === 'superadmin'"
                      @click="editAdmin(admin)"
                    >
                      编辑
                    </button>
                    <button 
                      class="action-btn status-btn" 
                      :disabled="admin.role === 'superadmin'"
                      @click="toggleAdminStatus(admin)"
                    >
                      {{ admin.status === 'active' ? '禁用' : '启用' }}
                    </button>
                    <button 
                      class="action-btn delete-btn" 
                      :disabled="admin.role === 'superadmin' || admins.length <= 1"
                      @click="deleteAdmin(admin)"
                    >
                      删除
                    </button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
          
          <!-- 空状态 -->
          <div v-if="admins.length === 0" class="empty-state">
            <i class="fa fa-user-circle"></i>
            <p>暂无管理员账户</p>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 系统信息 -->
    <div v-if="activeTab === 'system'" class="settings-content">
      <div class="settings-card">
        <h2 class="card-title">系统信息</h2>
        <div class="system-info">
          <div class="info-group">
            <div class="info-item">
              <span class="info-label">系统版本</span>
              <span class="info-value">{{ systemInfo.version }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">数据库版本</span>
              <span class="info-value">{{ systemInfo.dbVersion }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">最后更新</span>
              <span class="info-value">{{ formatDate(systemInfo.lastUpdate) }}</span>
            </div>
          </div>
          <div class="info-group">
            <div class="info-item">
              <span class="info-label">服务器时间</span>
              <span class="info-value">{{ currentTime }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">运行状态</span>
              <span class="info-value status-active">{{ systemInfo.status }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">运行时长</span>
              <span class="info-value">{{ systemInfo.uptime }}</span>
            </div>
          </div>
        </div>
        
        <h2 class="card-title mt-30">统计信息</h2>
        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-icon users-icon">
              <i class="fa fa-users"></i>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ stats.totalUsers }}</div>
              <div class="stat-label">注册用户</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon videos-icon">
              <i class="fa fa-video-camera"></i>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ stats.totalVideos }}</div>
              <div class="stat-label">视频数量</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon comments-icon">
              <i class="fa fa-comments"></i>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ stats.totalComments }}</div>
              <div class="stat-label">评论数量</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon views-icon">
              <i class="fa fa-eye"></i>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ stats.totalViews }}</div>
              <div class="stat-label">总浏览量</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 添加/编辑管理员对话框 -->
    <div v-if="showAddAdminDialog || showEditAdminDialog" class="dialog-overlay" @click="closeAdminDialog">
      <div class="dialog" @click.stop>
        <div class="dialog-header">
          <h3>{{ showEditAdminDialog ? '编辑管理员' : '添加管理员' }}</h3>
          <button class="close-button" @click="closeAdminDialog">
            <i class="fa fa-times"></i>
          </button>
        </div>
        <div class="dialog-content">
          <form @submit.prevent="submitAdminForm">
            <div class="form-row">
              <div class="form-group">
                <label>用户名</label>
                <input 
                  v-model="adminForm.username" 
                  type="text" 
                  required 
                  :disabled="showEditAdminDialog"
                />
              </div>
              <div class="form-group">
                <label>邮箱</label>
                <input v-model="adminForm.email" type="email" required />
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>
                  {{ showEditAdminDialog ? '新密码（留空表示不修改）' : '密码' }}
                </label>
                <input 
                  v-model="adminForm.password" 
                  type="password" 
                  :required="!showEditAdminDialog"
                  :placeholder="showEditAdminDialog ? '留空表示不修改' : ''"
                />
              </div>
              <div class="form-group">
                <label>
                  {{ showEditAdminDialog ? '确认新密码（留空表示不修改）' : '确认密码' }}
                </label>
                <input 
                  v-model="adminForm.confirmPassword" 
                  type="password" 
                  :required="!showEditAdminDialog"
                  :placeholder="showEditAdminDialog ? '留空表示不修改' : ''"
                />
              </div>
            </div>
            <div v-if="!showEditAdminDialog" class="form-group">
              <label>角色</label>
              <select v-model="adminForm.role">
                <option value="admin">管理员</option>
                <option v-if="isSuperAdmin" value="superadmin">超级管理员</option>
              </select>
            </div>
            <div class="form-group">
              <label>状态</label>
              <select v-model="adminForm.status">
                <option value="active">活跃</option>
                <option value="inactive">禁用</option>
              </select>
            </div>
            <div class="dialog-footer">
              <button type="button" class="cancel-button" @click="closeAdminDialog">取消</button>
              <button type="submit" class="save-button">{{ showEditAdminDialog ? '更新' : '添加' }}</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'SettingsView',
  data() {
    return {
      tabs: [
        { id: 'basic', name: '基本设置' },
        { id: 'admins', name: '管理员管理' },
        { id: 'system', name: '系统信息' },
      ],
      activeTab: 'basic',
      // 基本设置
      basicSettings: {
        siteName: '视频分享平台',
        siteUrl: 'https://example.com',
        siteDescription: '一个专业的视频分享平台，提供优质的视频内容和用户体验。',
        videosPerPage: 20,
        commentModeration: 'manual',
        enableRegistration: true,
        enableComments: true,
        enableUploads: true,
      },
      // 原始基本设置（用于重置）
      originalBasicSettings: {},
      // 管理员列表
      admins: [
        {
          id: 'admin1',
          username: 'admin',
          email: 'admin@example.com',
          password: 'admin123', // 实际应用中应该是哈希值
          role: 'superadmin',
          status: 'active',
          createdTime: '2024-01-01T00:00:00Z',
        },
      ],
      showAddAdminDialog: false,
      showEditAdminDialog: false,
      adminForm: {
        id: '',
        username: '',
        email: '',
        password: '',
        confirmPassword: '',
        role: 'admin',
        status: 'active',
      },
      // 系统信息
      systemInfo: {
        version: '1.0.0',
        dbVersion: '2.0',
        lastUpdate: '2024-01-01T00:00:00Z',
        status: '运行中',
        uptime: '10天 5小时 30分钟',
      },
      // 统计信息
      stats: {
        totalUsers: 1256,
        totalVideos: 589,
        totalComments: 3421,
        totalViews: 156789,
      },
      currentTime: '',
    }
  },
  computed: {
    isSuperAdmin() {
      // 实际应用中应该根据当前登录用户判断
      return true
    },
  },
  mounted() {
    // 保存原始设置用于重置
    this.originalBasicSettings = { ...this.basicSettings }
    
    // 更新当前时间
    this.updateCurrentTime()
    this.timeInterval = setInterval(this.updateCurrentTime, 1000)
  },
  beforeUnmount() {
    if (this.timeInterval) {
      clearInterval(this.timeInterval)
    }
  },
  methods: {
    updateCurrentTime() {
      this.currentTime = new Date().toLocaleString('zh-CN')
    },
    formatDate(dateString) {
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    },
    saveBasicSettings() {
      // 在实际应用中，这里应该调用API保存设置
      alert('基本设置已保存！')
    },
    resetBasicSettings() {
      this.basicSettings = { ...this.originalBasicSettings }
    },
    editAdmin(admin) {
      this.adminForm = { 
        ...admin, 
        password: '', 
        confirmPassword: '', 
      }
      this.showEditAdminDialog = true
    },
    toggleAdminStatus(admin) {
      const newStatus = admin.status === 'active' ? 'inactive' : 'active'
      if (confirm(`确定要${newStatus === 'active' ? '启用' : '禁用'}管理员 "${admin.username}" 吗？`)) {
        // 在实际应用中，这里应该调用API
        admin.status = newStatus
      }
    },
    deleteAdmin(admin) {
      if (this.admins.length <= 1) {
        alert('至少需要保留一个管理员账户！')
        return
      }
      
      if (confirm(`确定要删除管理员 "${admin.username}" 吗？此操作不可撤销！`)) {
        // 在实际应用中，这里应该调用API
        const index = this.admins.findIndex(a => a.id === admin.id)
        if (index > -1) {
          this.admins.splice(index, 1)
        }
      }
    },
    closeAdminDialog() {
      this.showAddAdminDialog = false
      this.showEditAdminDialog = false
      this.resetAdminForm()
    },
    resetAdminForm() {
      this.adminForm = {
        id: '',
        username: '',
        email: '',
        password: '',
        confirmPassword: '',
        role: 'admin',
        status: 'active',
      }
    },
    submitAdminForm() {
      // 密码验证
      if (this.adminForm.password && this.adminForm.password !== this.adminForm.confirmPassword) {
        alert('两次输入的密码不一致！')
        return
      }
      
      if (this.showEditAdminDialog) {
        // 编辑管理员
        const index = this.admins.findIndex(a => a.id === this.adminForm.id)
        if (index > -1) {
          const updatedAdmin = { ...this.admins[index], ...this.adminForm }
          // 如果密码为空，则不更新密码
          if (!this.adminForm.password) {
            delete updatedAdmin.password
            delete updatedAdmin.confirmPassword
          }
          this.admins[index] = updatedAdmin
        }
      } else {
        // 添加管理员
        // 检查用户名是否已存在
        const existingAdmin = this.admins.find(a => a.username === this.adminForm.username)
        if (existingAdmin) {
          alert('用户名已存在！')
          return
        }
        
        const newAdmin = {
          ...this.adminForm,
          id: 'admin' + (this.admins.length + 1),
          createdTime: new Date().toISOString(),
        }
        delete newAdmin.confirmPassword
        this.admins.push(newAdmin)
      }
      
      this.closeAdminDialog()
      alert(this.showEditAdminDialog ? '管理员信息已更新！' : '管理员已添加！')
    },
  },
}
</script>

<style scoped>
.settings-container {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  color: #2c3e50;
  margin: 0;
  font-size: 24px;
}

/* 标签导航 */
.settings-tabs {
  display: flex;
  gap: 0;
  background: #f8f9fa;
  border-radius: 6px;
  padding: 4px;
  margin-bottom: 20px;
}

.tab-button {
  padding: 12px 24px;
  border: none;
  background: transparent;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  color: #7f8c8d;
  transition: all 0.3s;
}

.tab-button:hover {
  color: #3498db;
}

.tab-button.active {
  background: white;
  color: #3498db;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

/* 设置内容 */
.settings-content {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.settings-card {
  margin-bottom: 20px;
}

.card-title {
  color: #2c3e50;
  margin: 0 0 20px 0;
  font-size: 18px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.card-header .card-title {
  margin: 0;
  border-bottom: none;
  padding-bottom: 0;
}

.add-button {
  background: #3498db;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: background-color 0.3s;
}

.add-button:hover {
  background: #2980b9;
}

/* 表单样式 */
.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.form-group {
  flex: 1;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #34495e;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
}

.checkbox-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.checkbox-group input {
  width: auto;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 30px;
}

.reset-button,
.save-button {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: background-color 0.3s;
}

.reset-button {
  background: #ecf0f1;
  color: #7f8c8d;
}

.reset-button:hover {
  background: #bdc3c7;
}

.save-button {
  background: #3498db;
  color: white;
}

.save-button:hover {
  background: #2980b9;
}

/* 管理员表格 */
.admins-table {
  width: 100%;
  border-collapse: collapse;
}

.admins-table th,
.admins-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.admins-table th {
  background: #f8f9fa;
  font-weight: 600;
  color: #2c3e50;
}

.admins-table tr:hover {
  background: #f8f9fa;
}

.role-badge,
.status-badge {
  padding: 3px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.role-badge.superadmin {
  background: #9b59b6;
  color: white;
}

.role-badge.admin {
  background: #3498db;
  color: white;
}

.status-badge.active {
  background: #2ecc71;
  color: white;
}

.status-badge.inactive {
  background: #95a5a6;
  color: white;
}

.table-actions {
  display: flex;
  gap: 5px;
}

.action-btn {
  padding: 5px 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  font-weight: 500;
  transition: background-color 0.3s;
}

.action-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.edit-btn {
  background: #3498db;
  color: white;
}

.edit-btn:hover:not(:disabled) {
  background: #2980b9;
}

.status-btn {
  background: #f39c12;
  color: white;
}

.status-btn:hover:not(:disabled) {
  background: #e67e22;
}

.delete-btn {
  background: #e74c3c;
  color: white;
}

.delete-btn:hover:not(:disabled) {
  background: #c0392b;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #95a5a6;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 15px;
  opacity: 0.5;
}

/* 系统信息 */
.system-info {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.info-group {
  background: #f8f9fa;
  border-radius: 6px;
  padding: 15px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #eee;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  color: #7f8c8d;
  font-size: 14px;
}

.info-value {
  color: #34495e;
  font-weight: 500;
  font-size: 14px;
}

.info-value.status-active {
  color: #2ecc71;
}

.mt-30 {
  margin-top: 30px;
}

/* 统计卡片 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.stat-card {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 15px;
  transition: transform 0.3s, box-shadow 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.users-icon {
  background: #3498db;
}

.videos-icon {
  background: #e74c3c;
}

.comments-icon {
  background: #2ecc71;
}

.views-icon {
  background: #f39c12;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
}

.stat-label {
  color: white;
  font-size: 14px;
}

/* 对话框 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.dialog-header h3 {
  margin: 0;
  color: #2c3e50;
}

.close-button {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #95a5a6;
}

.dialog-content {
  padding: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 30px;
}

.cancel-button {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  background: #ecf0f1;
  color: #7f8c8d;
  transition: background-color 0.3s;
}

.cancel-button:hover {
  background: #bdc3c7;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-row {
    flex-direction: column;
  }
  
  .settings-tabs {
    overflow-x: auto;
    padding: 4px 4px 4px 10px;
  }
  
  .tab-button {
    white-space: nowrap;
    min-width: 100px;
  }
  
  .admins-table {
    font-size: 14px;
  }
  
  .admins-table th,
  .admins-table td {
    padding: 8px;
  }
  
  .table-actions {
    flex-direction: column;
    gap: 3px;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .stat-card {
    padding: 15px;
  }
  
  .stat-icon {
    width: 40px;
    height: 40px;
    font-size: 20px;
  }
  
  .stat-number {
    font-size: 20px;
  }
}

@media (max-width: 480px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .admins-table {
    font-size: 12px;
  }
  
  .info-group {
    grid-column: 1 / -1;
  }
}
</style>